﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: Normalize.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-09-26 4:27 PM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

namespace BOL.Linq.Probability
{
    public static partial class Probability
    {
        public static IDictionary<TKey, double> Normalize<TKey>(this IDictionary<TKey, double> probabilityTable)
        {
            if (probabilityTable.Any(x => x.Value < 0))
                throw new ArgumentOutOfRangeException("probabilityTable", "Probability is expected to be positive.");

            var sum = probabilityTable.Sum(x => x.Value);

            if (Math.Abs(sum - 1) > 1e-8)
                return probabilityTable.ToDictionary(x => x.Key, x => x.Value / sum);
            
            if (Math.Abs(sum) < 1e-8)
                return probabilityTable.ToDictionary(x => x.Key, x => 1.0 / probabilityTable.Count);

            return probabilityTable;
        }
    }
}
